import logging
import os
import tempfile
from datetime import datetime
from config import config

def setup_logger(name: str = "video_deduplication"):
    """配置日志记录器"""
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    # 创建文件处理器
    os.makedirs(os.path.dirname("logs/process.log"), exist_ok=True)
    file_handler = logging.FileHandler("logs/process.log")
    file_handler.setLevel(logging.INFO)

    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)

    # 创建格式化器并添加到处理器
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # 清除旧的处理器并添加新的处理器
    if logger.handlers:
        logger.handlers = []
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger

def generate_temp_path(prefix: str = "temp", suffix: str = ".mp4"):
    """生成唯一的临时文件路径"""
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
    os.makedirs("temp", exist_ok=True)
    return os.path.join("temp", f"{prefix}_{timestamp}{suffix}")

def run_command(command: str):
    """执行系统命令并记录输出"""
    import subprocess
    logger = setup_logger()
    try:
        result = subprocess.run(command, shell=True, check=True,
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                text=True)
        logger.debug(f"命令执行成功: {command}")
        logger.debug(f"标准输出: {result.stdout}")
        return result.stdout
    except subprocess.CalledProcessError as e:
        logger.error(f"命令执行失败: {command}")
        logger.error(f"错误输出: {e.stderr}")
        raise